#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

mutex mtx;
condition_variable cv;
int current_printer = 1; // 表示当前应该打印的线程编号

void print_number(int id) {
    int n = 10;
    while (n --> 0) {
        unique_lock<mutex> lock(mtx);
        //cout << "fuck" << endl;
        cout.flush();
        cv.wait(lock, [&]{ return current_printer == id; }); // 等待当前打印机编号等于线程编号

        // 打印数字并换行，若达到10次则退出循环
        cout << id << " ";
        cout.flush(); // 刷新输出缓冲区，确保数字立即打印出来
        // 更新当前应该打印的线程编号
        current_printer = (current_printer == 3) ? 1 : current_printer + 1;

        cv.notify_all(); // 通知其他线程
    }
}

int main() {
    thread t1(print_number, 1);
    thread t2(print_number, 2);
    thread t3(print_number, 3);

    t1.join();
    t2.join();
    t3.join();

    cout << endl << "Finished printing numbers 1 to 10 for each thread." << endl;

    return 0;
}